﻿using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Threading.Tasks;
using Common.AppException;
using Common.Dto;
using Common.Identity;
using Demo03.RestClient;
using Demo03.RestClient.Dto;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Nacos.V2;

namespace Demo03.Controller;

/// <summary>
/// 服务调用接口
/// </summary>
public class NacosServiceController
{
    /// <summary>
    /// nacos 服务发现
    /// </summary>
    private readonly INacosNamingService _namingService;

    /// <summary>
    /// HttpClient工厂
    /// </summary>
    private readonly IHttpClientFactory _httpClientFactory;

    /// <summary>
    /// 日志
    /// </summary>
    private readonly ILogger<NacosServiceController> _logger;

    private readonly ITestClient _testClient;

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="namingService"></param>
    /// <param name="httpClientFactory"></param>
    /// <param name="logger"></param>
    /// <param name="testClient"></param>
    public NacosServiceController(INacosNamingService namingService, IHttpClientFactory httpClientFactory,
        ILogger<NacosServiceController> logger, ITestClient testClient)
    {
        _namingService = namingService;
        _httpClientFactory = httpClientFactory;
        _logger = logger;
        _testClient = testClient;
    }

    /// <summary>
    /// 远程调用springboot3接口
    /// </summary>
    /// <returns></returns>
    [HttpGet("test-invoke-spring-boot3-service")]
    public async Task<Result<Dictionary<string, object>?>> TestInvokeSpringBoot3()
    {
        var serviceName = "springboot3-demo01";
        var token =
            "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjb21wYW55Q29kZSI6InBhY3RlcmEiLCJ1diI6IkZCRTQ4RDY2Q0QiLCJ1c2VyX25hbWUiOiJDb2RlVXNlclByaW5jaXBhbChjb21wYW55Q29kZT1wYWN0ZXJhLCB1c2VybmFtZT1QMDA4ODg5MCkiLCJsYW5ndWFnZSI6InpoLWNuIiwiZGlzcGxheV9uYW1lIjoi566h55CG5ZGY55So5oi3IiwibW9iaWxlTWFpblBhZ2VVcmwiOiJodHRwczovL21vYmlsZS1wb3J0YWwuc3VwZXJkeHAuY29tLyIsInVzZXJJZCI6IjQ2IiwiYXV0aG9yaXRpZXMiOltdLCJwbGF0Zm9ybSI6dHJ1ZSwiY2xpZW50X2lkIjoicGFjdGVyYSIsImNvbXBhbnlDb2RlX2FsaWFzIjoiIiwic2NvcGUiOlsiYWxsIl0sInVzZXJVdWlkIjoicGFjdGVyYV9zdXBwZXJVc2VyIiwiZXhwIjoxNzA4MjYxNjM0LCJtYWluUGFnZVVybCI6Imh0dHBzOi8vZGV2LXBhY3RlcmEuc3VwZXJkeHAuY29tLyIsImp0aSI6ImdGajFTazhUVlpKS1lyV0RhSkxQRWQ1RWd4QSIsInVzZXJfYWdlbnQiOm51bGwsInVzZXJuYW1lIjoiUDAwODg4OTAiLCJzcmNfY2xpZW50X2lkIjoiIn0.dh1TDYfkucFiVqVdditlne_H4cEYNU8zuNbzaJqm9zU";

        // SelectOneHealthyInstance 使用预定义的负载平衡策略。
        var instance = await _namingService.SelectOneHealthyInstance(serviceName);
        var host = $"{instance.Ip}:{instance.Port}";
        var baseUrl = instance.Metadata.TryGetValue("secure", out _) ? $"https://{host}" : $"http://{host}";
        _logger.LogInformation("baseUrl: {@baseUrl}", baseUrl);

        var url = $"{baseUrl}/test";
        var httpClient = _httpClientFactory.CreateClient();
        httpClient.DefaultRequestHeaders.Authorization =
            new AuthenticationHeaderValue("Bearer", IdentityContext.Current?.BearerToken);

        var fromJsonAsync = await httpClient.GetFromJsonAsync<Dictionary<string, object>>(url);
        return Result.Success(fromJsonAsync);
    }

    /// <summary>
    /// 使用RestClient调用
    /// </summary>
    /// <returns></returns>
    [HttpGet("invoke-by-rest-client")]
    public async Task<Result<Dictionary<string, object>>> InvokeByRestClient()
    {
        var test = await _testClient.Test();
        return Result.Success(test);
    }


    /// <summary>
    /// 根据id查询用户
    /// </summary>
    /// <returns></returns>
    [HttpGet("query-user-by-id")]
    public async Task<Result<UserDto>> QueryUserById([Required] int? id)
    {
        var queryResult = await _testClient.QueryUserDto(id.Value);
        if (queryResult.Code != 200)
        {
            throw new RemoteCallException(queryResult.Message, queryResult.Code);
        }

        return Result.Success(queryResult.Data);
    }
}